package com.achao.achaomq.listener;

import com.achao.achaomq.constants.RocketMqConstant;
import com.achao.achaomq.dao.LogDao;
import com.achao.achaomq.entity.LogInterRecordPO;
import com.achao.achaomq.exception.CommonException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

/**
 * 日志消费者
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(
    topic = RocketMqConstant.ACHAO_LOG_RECORD,
    consumerGroup = RocketMqConstant.ACHAO_LOG_RECORD,
    messageModel = MessageModel.CLUSTERING
)
public class LogConsumer implements RocketMQListener<HashMap<String,Object>> {

    @Autowired
    private LogDao logDao;

    /**
     * 消费日志
     * @param mqMap
     */
    @Override
    public void onMessage(HashMap<String, Object> mqMap) {
        log.info("消费者监听进入:{}",mqMap);
        if(!mqMap.isEmpty()){
            log.info("消费数据不为空，开始消费...");
            LogInterRecordPO log = LogInterRecordPO.builder()
                    .apiModel(String.valueOf(mqMap.get("apiModel")))
                    .apiCode(String.valueOf(mqMap.get("apiCode")))
                    .apiName(String.valueOf(mqMap.get("apiName")))
                    .timeConsumption(Long.valueOf(mqMap.get("timeConsumption").toString()))
                    .lastUpdate_time(new Date())
                    .build();
            try{
                logDao.logSave(log);
            }catch(Exception e){
                throw new CommonException("RocketMQ日志插入失败！！");
            }
        }
    }
}
